<template>
  <view class="container tab-bar">
    <scroll-view scroll-y>
      <!-- 头部标签页 -->
      <tabs :tabs="tabs" :tabsFixed="true" v-on:tabsItemTap="tabsItemTap">
        <view v-show="tabs[0].isActive" class="tabs-time">
          <text
            class="iconfont icon-arrow-left-filling time-pre"
            @click.stop="dateChange('weeks', 'up')"
          ></text>
          <text class="time-text">{{ dateWeeksText }}</text>
          <text
            class="iconfont icon-arrow-right-filling time-next"
            @click.stop="dateChange('weeks', 'next')"
          ></text>
        </view>

        <view v-show="tabs[1].isActive" class="tabs-time">
          <text
            class="iconfont icon-arrow-left-filling time-pre"
            @click.stop="dateChange('months', 'up')"
          ></text>
          <text class="time-text">{{ dateMonthsText }}</text>
          <text
            class="iconfont icon-arrow-right-filling time-next"
            @click.stop="dateChange('months', 'next')"
          ></text>
        </view>

        <view v-show="tabs[2].isActive" class="tabs-time">
          <text
            class="iconfont icon-arrow-left-filling time-pre"
            @click.stop="dateChange('years', 'up')"
          ></text>
          <text class="time-text">{{ dateYearsText }}</text>
          <text
            class="iconfont icon-arrow-right-filling time-next"
            @click.stop="dateChange('years', 'next')"
          ></text>
        </view>
      </tabs>

      <!-- 任务详情 -->
      <view class="task-list">
        <view class="task-item task-all">
          <text>{{ statisticalInfo.total }}</text>
          <text>总任务</text>
        </view>
        <view class="task-item task-done">
          <text>{{ statisticalInfo.finish }}</text>
          <text>完成任务</text>
        </view>
        <view class="task-item task-rate">
          <text>{{ statisticalInfo.percentage }}%</text>
          <text>完成任务率</text>
        </view>
      </view>

      <!-- 图像表格 -->
      <view class="table-figure">
        <!-- 树状图 -->
        <view class="tree-box">
          <uni-ec-canvas
            ref="canvas-tree"
            class="uni-ec-canvas"
            :ec="ec"
          ></uni-ec-canvas>
          <!-- :forceUseOldCanvas="true" -->
        </view>
        <!-- 饼图 -->
        <!-- <view class="pie-box">
          <uni-ec-canvas
            ref="canvas-pie"
            class="uni-ec-canvas"
            :ec="ec2"
            :forceUseOldCanvas="true"
          ></uni-ec-canvas>
        </view> -->
      </view>
    </scroll-view>
    <!-- 底部导航栏 -->
    <TabBar :tabbar="tabbar" />
  </view>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import tabs from "../../component/Tabs/Tabs";
import TabBar from "../../component/TabBar/TabBar";
// 导入 echarts 插件
import uniEcCanvas from "../../component/uni-ec-canvas/uni-ec-canvas";
// 引入接口文件
const {
  getWorkWeeklyStatistic,
  getWorkMonthlyStatistic,
  getWorkAnnalStatistic,
} = require("../../api/statistical/statistical");
const { format, debounce, cloneObject } = require("../../utils/utils");

export default {
  components: { TabBar, tabs, uniEcCanvas },
  data() {
    return {
      tabs: [
        {
          id: 0,
          value: "周",
          isActive: true,
        },
        {
          id: 1,
          value: "月",
          isActive: false,
        },
        {
          id: 2,
          value: "年",
          isActive: false,
        },
      ],
      // 日期 周 文本
      dateWeeksText: "",
      // 日期 月 文本
      dateMonthsText: "",
      // 日期 年 文本
      dateYearsText: "",
      // 真实需要的时间
      dateWeeksValue: "",
      dateMonthsValue: "",
      dateYearsValue: "",
      // 统计数据信息
      statisticalInfo: {
        total: 0,
        finish: 0,
        percentage: 0,
      },
      echartsInfo: {},
      // 树状图配置
      ec: {
        lazyLoad: true,
        option: {
          title: {
            text: "本周完成任务情况",
            x: "left",
            textStyle: {
              color: "#999999",
              fontFamily: "PingFang SC",
              fontWeight: 500,
              fontSize: 14,
            },
          },
          tooltip: {
            trigger: "axis",
            formatter: "{b}\r\n{c0}个",
            axisPointer: {
              type: "line",
              axis: "x",
              label: {
                backgroundColor: "#000000",
              },
            },
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
            // 是否显示坐标轴刻度
            axisTick: {
              show: false,
            },
            splitLine: {
              // 网格线
              show: false,
            },
          },
          yAxis: {
            type: "value",
            min: 0,
            splitLine: {
              // 网格线
              show: true,
              symbol: "arrow",
              symbolSize: [0, 0],
              lineStyle: {
                color: "#999",
                type: "solid",
              },
            },
          },
          series: [
            {
              name: "本周完成任务情况",
              type: "bar",
              barWidth: 10,
              showBackground: false,
              itemStyle: {
                borderRadius: [50, 50, 0, 0],
              },
              data: [],
            },
          ],
        },
      },
      // 饼状图配置
      // ec2: {
      //   lazyLoad: true,
      //   option: {
      //     title: {
      //       text: "完成紧急任务情况",
      //       x: "left",
      //       textStyle: {
      //         fontFamily: "PingFang SC",
      //         fontWeight: 500,
      //         color: "#999999",
      //         fontSize: 14,
      //         // align: "center",
      //       },
      //     },
      //     legend: {
      //       orient: "vertical",
      //       top: "middle",
      //       right: "10%",
      //       data: ["高", "中", "低", "无"],
      //     },
      //     series: [
      //       {
      //         name: "完成紧急任务情况",
      //         type: "pie",
      //         radius: ["35%", "65%"],
      //         center: ["35%", "50%"],
      //         label: {
      //           position: "outside",
      //           color: "#999999",
      //           normal: {
      //             show: false,
      //           },
      //           emphasis: {
      //             show: true,
      //           },
      //           fontSize: 10,
      //         },
      //         labelLine: {
      //           normal: {
      //             show: false,
      //           },
      //           emphasis: {
      //             show: true,
      //           },
      //         },
      //         data: [
      //           {
      //             value: 3321,
      //             name: "高",
      //             itemStyle: {
      //               normal: { color: "#28d094" },
      //               emphasis: { color: "#28d094" },
      //             },
      //           },
      //           {
      //             value: 1148,
      //             name: "中",
      //             itemStyle: {
      //               normal: { color: "#ffc71c" },
      //               emphasis: { color: "#ffc71c" },
      //             },
      //           },
      //           {
      //             value: 2532,
      //             name: "低",
      //             itemStyle: {
      //               normal: { color: "#1e9ff2" },
      //               emphasis: { color: "#1e9ff2" },
      //             },
      //           },
      //           {
      //             value: 1148,
      //             name: "无",
      //             itemStyle: {
      //               normal: { color: "#ff6262" },
      //               emphasis: { color: "#ff6262" },
      //             },
      //           },
      //         ],
      //       },
      //     ],
      //   },
      // },
    };
  },
  computed: {
    ...mapState(["tabbar", "isGetDataAgain"]),
  },
  methods: {
    ...mapMutations(["editTabbar", "editIsGetDataAgain"]),
    // tab栏改变
    tabsItemTap(index) {
      // 设置选中状态
      this.tabs.forEach(item => {
        item.id == index ? (item.isActive = true) : (item.isActive = false);
      });

      switch (index) {
        case 0:
          // 有数据时不用重新获取
          if (this.statisticalInfo.weeks) {
            this.ec = this.echartsInfo.weekEC;
            // 是否需要刷新数据
            if (this.isGetDataAgain) {
              this.getStatisticalInfo("weeks");
              this.editIsGetDataAgain(false);
            }
            break;
          }
          // 获取数据
          this.getStatisticalInfo("weeks");
          break;

        case 1:
          // 有数据时不用重新获取
          if (this.statisticalInfo.months) {
            this.ec = this.echartsInfo.monthEC;
            // 是否需要刷新数据
            if (this.isGetDataAgain) {
              this.getStatisticalInfo("months");
              this.editIsGetDataAgain(false);
            }
            break;
          }
          // 获取数据
          this.getStatisticalInfo("months");
          break;

        case 2:
          // 有数据时不用重新获取
          if (this.statisticalInfo.years) {
            this.ec = this.echartsInfo.yearEC;
            // 是否需要刷新数据
            if (this.isGetDataAgain) {
              this.getStatisticalInfo("years");
              this.editIsGetDataAgain(false);
            }
            break;
          }
          // 获取数据
          this.getStatisticalInfo("years");
          break;
      }
    },
    // 日期改变
    dateChange(datetype, calculate) {
      let date = ""; // 当前显示的日期
      let newDate = ""; // 新的日期
      let yearValue = ""; // 年份

      switch (datetype) {
        case "weeks":
          date = new Date(this.dateWeeksValue);

          calculate == "up"
            ? // 获取当前时间-7天后的时间
              (newDate = format(date.setDate(date.getDate() - 7), "yyyy-MM-dd"))
            : // 获取当前时间+7天后的时间
              (newDate = format(
                date.setDate(date.getDate() + 7),
                "yyyy-MM-dd"
              ));

          // 设置时间
          yearValue = new Date(newDate).getFullYear();
          let week = this.getYearWeek(newDate);
          this.dateWeeksText = `${yearValue}年第${week}周`;
          this.dateWeeksValue = newDate;
          break;

        case "months":
          date = new Date(this.dateMonthsValue);

          calculate == "up"
            ? // 获取当前时间-1月后的时间
              (newDate = format(
                date.setMonth(date.getMonth() - 1),
                "yyyy-MM-dd"
              ))
            : // 获取当前时间+1月后的时间
              (newDate = format(
                date.setMonth(date.getMonth() + 1),
                "yyyy-MM-dd"
              ));

          // 设置时间
          yearValue = new Date(newDate).getFullYear();
          let month = new Date(newDate).getMonth() + 1;
          this.dateMonthsText = `${yearValue}年第${month}月`;
          this.dateMonthsValue = `${yearValue}-${month}`;
          break;

        case "years":
          date = new Date(this.dateYearsValue);

          calculate == "up"
            ? // 获取当前时间-1年后的时间
              (newDate = format(
                date.setFullYear(date.getFullYear() - 1),
                "yyyy"
              ))
            : // 获取当前时间+1年后的时间
              (newDate = format(
                date.setFullYear(date.getFullYear() + 1),
                "yyyy"
              ));

          // 设置时间
          this.dateYearsText = `${newDate}年`;
          this.dateYearsValue = newDate;
          break;
      }

      // 获取数据
      this.getStatisticalInfo(datetype);
    },
    // 获取第n年第n周
    getYearWeek(datetime) {
      let d1 = new Date(datetime);
      let d2 = new Date(datetime);
      d2.setMonth(0);
      d2.setDate(1);
      let rq = d1 - d2;
      let days = Math.ceil(rq / (24 * 60 * 60 * 1000));
      let num = Math.ceil(days / 7);
      return num;
    },
    // 获取月份的天数
    getMonthDay(datetime) {
      var year = datetime.getFullYear();
      var month = datetime.getMonth() + 1;
      var d = new Date(year, month, 0);
      return d.getDate();
    },
    // 页面初始化
    pageInit() {
      const date = new Date();

      // 周
      this.dateWeeksText = `${date.getFullYear()}年第${this.getYearWeek(
        format(date, "yyyy-MM-dd")
      )}周`;
      this.dateWeeksValue = format(date, "yyyy-MM-dd");

      // 月
      this.dateMonthsText = `${date.getFullYear()}年第${date.getMonth() + 1}月`;
      this.dateMonthsValue = format(date, "yyyy-MM");

      // 年
      this.dateYearsText = `${date.getFullYear()}年`;
      this.dateYearsValue = format(date, "yyyy");

      // 获取当前周的数据
      this.getStatisticalInfo("weeks");
    },

    // 防抖 获取统计数据
    getStatisticalInfo: debounce(function (datetype) {
      let params = {};
      let xAxis = [];
      let seriesData = [];

      switch (datetype) {
        case "weeks":
          // 请求参数
          params = {
            date: this.dateWeeksValue,
            code: uni.getStorageSync("openId"),
          };
          getWorkWeeklyStatistic(params).then(
            res => {
              xAxis = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
              this.statisticalInfo.total = res.total;
              this.statisticalInfo.finish = res.finish;
              this.statisticalInfo.percentage = res.percentage;
              this.statisticalInfo.weeks = res;
              if (!res.data)
                return (this.ec.option.series[0].data = seriesData); // 没有data数据时

              for (let i = 0; i < xAxis.length; i++) {
                // 根据 week 匹配对应的星期天数
                seriesData[i] = res.data.reduce((data, item) => {
                  // 如果 week 等于 xAxis的下标 就表示匹配成功
                  if (i + 1 == item.week) {
                    data = {
                      value: item.count,
                      week: item.week,
                    };
                  }
                  return data;
                }, {});
              }

              // echarts 区域配置
              let dataZoom = [
                {
                  type: "inside",
                  start: 0,
                  end: 100,
                },
              ];

              this.ec.option.dataZoom = dataZoom;
              this.ec.option.xAxis.data = xAxis;
              this.ec.option.series[0].data = seriesData;
              // 取消this.ec 和 this.echartsInfo.yearEC 之间的栈指向同一个堆的问题
              this.echartsInfo.weekEC = cloneObject(this.ec);
            },
            err => {
              uni.showToast({ title: err, icon: "none" });
            }
          );
          break;

        case "months":
          // 请求参数
          params = {
            date: this.dateMonthsValue,
            code: uni.getStorageSync("openId"),
          };
          getWorkMonthlyStatistic(params).then(
            res => {
              this.statisticalInfo.total = res.total;
              this.statisticalInfo.finish = res.finish;
              this.statisticalInfo.percentage = res.percentage;
              this.statisticalInfo.months = res;
              if (!res.data)
                return (this.ec.option.series[0].data = seriesData); // 没有data数据时

              let dateMonthsValue = new Date(this.dateMonthsValue);
              let dateMonths = dateMonthsValue.getMonth() + 1;
              let monthDay = this.getMonthDay(dateMonthsValue);
              // 添加日期天数
              for (let i = 1; i <= monthDay; i++) {
                i < 10
                  ? xAxis.push(dateMonths + "/0" + i)
                  : xAxis.push(dateMonths + "/" + i);
              }

              // 数据匹配
              for (let i = 0; i < xAxis.length; i++) {
                // 根据 任务日期 匹配对应的月份天数
                seriesData[i] = res.data.reduce((data, item) => {
                  // 把 2021-05-19 格式化成 5/19
                  let create_time =
                    item.create_time.substr(-5, 2) -
                    0 +
                    "/" +
                    item.create_time.substr(-2);
                  // 如果 任务日期 等于 xAxis的日期 就表示匹配成功
                  if (xAxis[i] == create_time) {
                    data = {
                      value: item.count,
                      create_time: create_time,
                    };
                  }
                  return data;
                }, {});
              }

              // echarts 区域配置
              let dataZoom = [
                {
                  type: "slider",
                  show: true,
                  start: 0,
                  end: 50,
                  handleSize: "30%",
                  backgroundColor: "rgba(47,69,84,0)",
                  handleIcon:
                    "path://M30.9,53.2C16.8,53.2,5.3,41.7,5.3,27.6S16.8,2,30.9,2C45,2,56.4,13.5,56.4,27.6S45,53.2,30.9,53.2z M30.9,3.5C17.6,3.5,6.8,14.4,6.8,27.6c0,13.3,10.8,24.1,24.101,24.1C44.2,51.7,55,40.9,55,27.6C54.9,14.4,44.1,3.5,30.9,3.5z M36.9,35.8c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H36c0.5,0,0.9,0.4,0.9,1V35.8z M27.8,35.8 c0,0.601-0.4,1-0.9,1h-1.3c-0.5,0-0.9-0.399-0.9-1V19.5c0-0.6,0.4-1,0.9-1H27c0.5,0,0.9,0.4,0.9,1L27.8,35.8L27.8,35.8z",
                  handleSize: "80%",
                },
              ];

              // 取消this.ec 和 this.echartsInfo.yearEC 之间的栈指向同一个堆的问题
              this.ec.option.dataZoom = dataZoom;
              this.ec.option.xAxis.data = xAxis;
              this.ec.option.series[0].data = seriesData;
              this.echartsInfo.monthEC = cloneObject(this.ec);
            },
            err => {
              uni.showToast({ title: err, icon: "none" });
            }
          );
          break;

        case "years":
          // 请求参数
          params = {
            date: this.dateYearsValue,
            code: uni.getStorageSync("openId"),
          };
          getWorkAnnalStatistic(params).then(
            res => {
              xAxis = [
                "01",
                "02",
                "03",
                "04",
                "05",
                "06",
                "07",
                "08",
                "09",
                "10",
                "11",
                "12",
              ];
              this.statisticalInfo.total = res.total;
              this.statisticalInfo.finish = res.finish;
              this.statisticalInfo.percentage = res.percentage;
              this.statisticalInfo.years = res;
              if (!res.data)
                return (this.ec.option.series[0].data = seriesData); // 没有data数据时

              // 数据匹配
              for (let i = 0; i < xAxis.length; i++) {
                // 根据 任务日期 匹配对应的月份
                seriesData[i] = res.data.reduce((data, item) => {
                  let create_time = item.create_time.substr(-2);
                  // 如果 任务日期 等于 xAxis的日期 就表示匹配成功
                  if (xAxis[i] == create_time) {
                    data = {
                      value: item.count,
                      create_time: create_time,
                    };
                  }
                  return data;
                }, {});
              }

              // echarts 区域配置
              let dataZoom = [
                {
                  type: "inside",
                  start: 0,
                  end: 100,
                },
              ];

              this.ec.option.dataZoom = dataZoom;
              this.ec.option.xAxis.data = xAxis;
              this.ec.option.series[0].data = seriesData;
              // 取消this.ec 和 this.echartsInfo.yearEC 之间的栈指向同一个堆的问题
              this.echartsInfo.yearEC = cloneObject(this.ec);
            },
            err => {
              uni.showToast({ title: err, icon: "none" });
            }
          );
          break;
      }
    }, 400),
  },
  onLoad() {
    // 设置TabBar
    this.editTabbar();
    // 页面初始化
    this.pageInit();

    setTimeout(() => {
      this.$refs["canvas-tree"].init();
      // this.$refs["canvas-pie"].init();
    }, 300);
  },
  onShow() {
    // if (this.isGetDataAgain) {
    let index = this.tabs.findIndex(item => item.isActive == true);
    switch (index) {
      case 0:
        this.getStatisticalInfo("weeks");
        break;
      case 1:
        this.getStatisticalInfo("months");
        break;
      case 2:
        this.getStatisticalInfo("years");
        break;
    }
    //   this.editIsGetDataAgain(false);
    // }
  },
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #fff;

  .tabs-time {
    margin-top: 40rpx;
    height: 40rpx;
    font-size: 28rpx;
    font-weight: bold;
    line-height: 40rpx;
    text-align: center;
    color: #333333;

    .time-text {
      padding: 0 36rpx;
    }

    .time-next {
      color: #999999;
    }
  }

  .task-list {
    display: flex;
    margin: 60rpx 0;

    .task-item {
      position: relative;
      flex: 1;
      display: flex;
      flex-direction: column;
      width: 192rpx;
      height: 192rpx;
      margin: 0 30rpx;
      padding: 40rpx 0 30rpx 30rpx;
      border-radius: 32rpx;
      overflow: hidden;
      font-size: 48rpx;
      font-weight: bold;
      color: #fff;

      &::after {
        content: "";
        position: absolute;
        right: -20rpx;
        bottom: -30rpx;
        width: 108rpx;
        height: 64rpx;
        background-color: #fff;
        border-radius: 30rpx 0 0 0;
        opacity: 0.2;
      }

      & > text:nth-child(1) {
        flex: 2;
        overflow: auto;
        max-width: 150rpx;
      }

      & > text:nth-child(2) {
        flex: 1;
        font-size: 24rpx;
        font-weight: 400;
      }
    }

    .task-all {
      background-color: #666ee8;
    }
    .task-done {
      background-color: #28d094;
    }
    .task-rate {
      background-color: #ff6262;
    }
  }

  .table-figure {
    .tree-box,
    .pie-box {
      position: relative;
      width: 100%;
      height: 650rpx;
      padding: 0 30rpx;
    }
  }
}
</style>
